<template>
  <div id="auditSuccessDialog">
    <el-dialog
      :title="dialogTitle"
      :visible.sync="auditSuccessDialogData.isShow"
      width="750px"
      :destroy-on-close="true"
      class="success-dialog"
    >
      <div class="form-box">
        <el-form
          ref="auditSuccessForm"
          :model="form"
          label-position="left"
          label-width="90px"
        >
          <el-form-item label="选择触达人群">
            <el-select
              v-model="selectValue"
              placeholder="全站用户"
              @change="selectChange"
            >
              <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <span
              class="red-text"
              v-if="selectValue === 'ALL' && touchType === 'SMS'"
              >*本次触达将产生实际费用，预计费用为：4.52万元</span
            >
          </el-form-item>
          <el-form-item
            v-if="
              auditSuccessDialogData.params.touchType === 'SMS' ||
                auditSuccessDialogData.params.touchType === 'PUSH'
            "
          >
            <div class="tips">
              注意：当前选择的触达方式为“{{ touchTypeName }}”。消息{{
                touchTypeName
              }}是收费项目，{{ touchTypeName }}将会产生实际费用！
            </div>
          </el-form-item>
          <el-form-item v-if="peopleSelectFlag" label="搜索人群组">
            <el-input
              v-model="searchParams.searchStr"
              class="search-input"
            ></el-input>
            <el-button
              type="success"
              icon="el-icon-search"
              class="search-btn"
              @click="searchStudentGroup"
            >
              查询
            </el-button>
            <div class="bottom">
              <!-- 表格部分 -->
              <el-table
                :data="peopleTableData"
                style="width: 100%"
                class="search-table"
              >
                <el-table-column
                  prop="id"
                  label="用户群（ID）"
                  width="200"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="name"
                  label="用户人群名称"
                  min-width="240"
                  align="center"
                ></el-table-column>
                <el-table-column label="操作" width="240" align="center">
                  <template slot-scope="scope">
                    <el-button @click="usePeople(scope.$index, scope.row)">
                      使用
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!--分页-全局组件-->
              <pageCom
                :searchParams="searchParams"
                :total="total"
                @searchList="getAllStudentGroup"
              ></pageCom>
              <!-- 已选择人群部分 -->
              <el-card>
                <div slot="header" class="clearfix">
                  <span>已选择人群</span>
                </div>
                <span
                  v-for="(item, index) in selectedPeople"
                  :key="index"
                  class="selected-people"
                >
                  <span class="tag-span success people-name">{{
                    item.name
                  }}</span>
                  <span
                    class="tag-span danger delete-btn"
                    @click="deleteSelect(index, item)"
                    >删除</span
                  >
                </span>
              </el-card>
              <div class="sms-tips" v-if="touchType === 'SMS'">
                {{ smsMsg }}
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="confirm">确 定</el-button>
        <el-button type="default" @click="auditSuccessDialogData.isShow = false"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'qs'
import {
  getTouchPeopleAPI,
  passEditAPI,
  passAuditAPI
} from '@/api/noticeManagement/pubNotice'
import {
  getMoneyByGroupIdsAPI,
  getSearchList
} from '@/api/userManagement/userManageAPI'
export default {
  props: ['auditSuccessDialogData'],
  data() {
    return {
      dialogTitle: '通知审核通过',
      selectOptions: [
        { label: '全站用户', value: 'ALL' },
        { label: '选择用户人群', value: 'STUDENT_GROUP' }
      ],
      selectValue: 'ALL',
      form: {},
      peopleSelectFlag: false,
      peopleTableData: [],
      selectedPeople: [],
      touchType: '',
      touchTypeName: '',
      noticeId: '',
      editFlag: false,
      searchParams: {
        pageNum: 1,
        pageSize: 10,
        searchStr: '',
        enable: true,
        notIds: []
      },
      total: 0,
      smsMsg: '加载中。。。'
    }
  },
  watch: {
    selectValue(val) {
      this.peopleSelectFlag = val === 'ALL' ? false : true
    }
  },
  mounted() {
    this.noticeId = this.auditSuccessDialogData.noticeId
    this.editFlag = this.auditSuccessDialogData.editFlag
    this.touchType = this.auditSuccessDialogData.params.touchType
    if (this.touchType === 'SMS') {
      this.touchTypeName = '短信'
    } else if (this.touchType === 'PUSH') {
      this.touchTypeName = '推送'
    }
    // 如果是编辑消息 改变标题和选中人群
    if (this.editFlag) {
      this.dialogTitle = '活动消息'
      this.getTouchPeople()
    }
    this.getMoneyByGroupIds()
  },
  methods: {
    // 获取用户人群
    getTouchPeople() {
      getTouchPeopleAPI(this.noticeId, (response) => {
        this.selectValue = response.studentGroupType
        this.selectedPeople = response.studentGroupsDtos
        this.getAllStudentGroup()
        if (this.touchType === 'SMS') {
          this.getMoneyByGroupIds()
        }
      })
    },
    // 获取所有用户人群
    getAllStudentGroup() {
      let params = this.searchParams
      let notIds = []
      this.selectedPeople.map((item) => {
        notIds.push(item.id)
      })
      params.notIds = notIds
      getSearchList(params, (response) => {
        this.peopleTableData = response.rows
        this.total = response.total
      })
    },
    // 页码改变
    changePage(page) {
      this.searchParams.pageNum = page
      this.getAllStudentGroup()
    },
    // 选择人群
    usePeople(index, row) {
      let totalPeopleNum = 0
      this.selectedPeople.map((item) => {
        totalPeopleNum += item.rulesNum
      })
      if (totalPeopleNum >= 27 && row.rulesNum > 0) {
        this.$message.error(
          `选择的用户组超出了最大用户规则数，规则数最大为27组，当前规则数${totalPeopleNum},新加入用户组规则数为${row.rulesNum}超过了27组`
        )
        return
      }
      this.peopleTableData.splice(index, 1)
      this.selectedPeople.push(row)
      this.getAllStudentGroup()
      if (this.touchType === 'SMS') {
        this.getMoneyByGroupIds()
      }
    },
    // 删除选中人群
    deleteSelect(index, selectItem) {
      this.selectedPeople.splice(index, 1)
      this.getAllStudentGroup()
      if (this.touchType === 'SMS') {
        this.getMoneyByGroupIds()
      }
    },
    // 确定按钮
    confirm() {
      let message = `<span style="color:red;font-weight:bold;">当前选择的触达方式为“${this.touchTypeName}” 消息${this.touchTypeName}是收费项目，${this.touchTypeName}将会产生实际费用！ 确定要使用“${this.touchTypeName}”方式发布通知吗？</span>`
      if (this.touchType === 'SMS' || this.touchType === 'PUSH') {
        this.$confirm(`${message}`, '系统提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '我确认',
          cancelButtonText: '我再想想',
          type: 'warning'
        })
          .then(() => {
            this.passRequest()
          })
          .catch(() => {})
      } else {
        this.passRequest()
      }
    },
    // 审核通过请求
    passRequest() {
      if (
        this.selectValue === 'STUDENT_GROUP' &&
        this.selectedPeople.length === 0
      ) {
        this.$message.error('请选择用户组')
        return
      }
      let id = []
      this.selectedPeople.map((item) => {
        id.push(item.id)
      })
      let params = {
        auditState: 'PASS',
        studentGroup: {
          studentGroupType: this.selectValue,
          id: id
        }
      }
      params = qs.stringify(params, { allowDots: true })
      if (this.editFlag) {
        // 编辑
        passEditAPI(
          this.noticeId,
          params,
          (response) => {
            this.$emit('refresh')
            this.auditSuccessDialogData.isShow = false
          },
          (response) => {
            this.$message({
              message: response.message,
              type: 'warning'
            })
          }
        )
      } else {
        // 审核通过
        passAuditAPI(
          this.noticeId,
          params,
          (response) => {
            this.$emit('refresh')
            this.auditSuccessDialogData.isShow = false
          },
          (response) => {
            this.$message({
              message: response.message,
              type: 'warning'
            })
          }
        )
      }
    },
    searchStudentGroup() {
      this.searchParams.pageNum = 1
      this.getAllStudentGroup()
    },
    selectChange(val) {
      if (val === 'STUDENT_GROUP') {
        this.getAllStudentGroup()
      }
    },
    getMoneyByGroupIds() {
      if (this.selectedPeople.length > 0) {
        this.smsMsg = '加载中。。。'
        let ids = []
        this.selectedPeople.map((item) => {
          ids.push(item.id)
        })
        let params = {
          ids: ids.join(',')
        }
        getMoneyByGroupIdsAPI(
          params,
          (response) => {
            this.smsMsg = response.msg
          },
          (response) => {
            this.$message.error(response.message)
          }
        )
      } else {
        this.smsMsg = '*本次触达将产生实际费用，预计费用为：0元；'
      }
    }
  }
}
</script>
<style lang="less">
#auditSuccessDialog {
  .form-box {
    th {
      line-height: 23px;
    }
    .bottom {
      margin-left: -90px;
      .el-table::before {
        height: 0;
      }
    }
    .el-card__header {
      padding: 4px 10px;
    }
    .page {
      margin-bottom: 15px;
    }
  }
  .tips {
    margin-top: -20px;
    font-size: 20px;
    color: red;
    font-weight: 600;
  }
  .search-input {
    width: 200px;
  }
  .search-btn {
    margin-left: 10px;
    width: 80px;
    height: 30px;
  }
  .search-table {
    margin-top: 10px;
    margin-bottom: 10px;
    max-height: 480px;
    overflow-y: auto;
  }
  .people-name {
    padding: 3px !important;
    border-top-right-radius: 0px !important;
    border-bottom-right-radius: 0px !important;
    cursor: pointer;
  }
  .delete-btn {
    padding: 3px !important;
    border-top-left-radius: 0px !important;
    border-bottom-left-radius: 0px !important;
    cursor: pointer;
  }
  .selected-people {
    display: inline-block;
    margin-right: 10px;
  }
  .red-text {
    margin-left: 5px;
    color: red;
  }
  .sms-tips {
    color: red;
  }
}
</style>
